package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * Author: Zheng
 * Date:   2024/1/27  11:58
 * Package：com.itheima.exception
 * Description：
 * Version：1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * @description： 全局异常拦截所有异常
     * @date：2024/1/27  12:08
     * @return：
     **/
    @ExceptionHandler(Exception.class)
    public Result ex(Exception e) {
        e.printStackTrace();
        return Result.error("出错啦，请联系管理员！");
    }


    @ExceptionHandler(DuplicateKeyException.class)
    public Result SQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error(message); //Duplicate entry '教研部' for key 'dept.name'
        return Result.error(message.split(" ")[2]+"已存在，请重新添加部门！");
    }
}
